package com.bwhk.splitdata.task;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.bwhk.splitdata.task.model.ItemFreq;


@Component
public class TaskManageJob  implements Job{
    private static Logger logger = LoggerFactory.getLogger(TaskManageJob.class);
   
    private static String JOB_GROUP_NAME = "IYW_JOBGROUP_NAME";  
    private static String TRIGGER_GROUP_NAME = "IYW_TRIGGERGROUP_NAME";
    private static List<ItemFreq> itemFreqList = new ArrayList<ItemFreq>();
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private Scheduler scheduler;
    public void executeTaskRefresh() {
    	try {
			String sql = "select iq.id,iq.descr,iq.script from iyw_watch_item_freq iq";
			List<ItemFreq> ifList = jdbcTemplate.query(sql, new RowMapper<ItemFreq>() {
			    public ItemFreq mapRow(ResultSet rs, int rowNum) throws SQLException {
			    	ItemFreq itemFreq = new ItemFreq();
			    	itemFreq.setId(rs.getInt("ID"));
			    	itemFreq.setDescr(rs.getString("DESCR"));
			    	itemFreq.setScript(rs.getString("SCRIPT"));
			        return itemFreq;  
			    }  
			});
			// 删除Job
			for (int i=0;i<itemFreqList.size();i++) {
				ItemFreq itemFreq = itemFreqList.get(i);
				if (!ifList.contains(itemFreq)) {
					String jobName = "JOB_ITEM_FREQ_"+itemFreq.getId();
					String triggerName = "TRIGGER_ITEM_FREQ_"+itemFreq.getId();
					JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);
					TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, TRIGGER_GROUP_NAME);
					scheduler.pauseTrigger(triggerKey);
					scheduler.unscheduleJob(triggerKey);
					scheduler.deleteJob(jobKey);
				}				
			}
			for (int i=0;i<ifList.size();i++) {
				ItemFreq itemFreq = ifList.get(i);
				if (itemFreq.getScript() == null || "".equals(itemFreq.getScript())) {
					continue;
				}
				// 更新Job
				if (itemFreqList.contains(itemFreq)) {
					String newCronExpression = itemFreq.getScript().trim();
					String jobName = "JOB_ITEM_FREQ_"+itemFreq.getId();
					String triggerName = "TRIGGER_ITEM_FREQ_"+itemFreq.getId();
					TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, TRIGGER_GROUP_NAME);
					CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
					if (trigger != null && !newCronExpression.equals(trigger.getCronExpression())) {
		                // 触发器  
		                TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
		                triggerBuilder.withIdentity(triggerName, TRIGGER_GROUP_NAME);
		                triggerBuilder.startNow();
		                // 触发器时间设定  
		                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(newCronExpression));
		                // 创建Trigger对象
		                trigger = (CronTrigger) triggerBuilder.build();
		                scheduler.rescheduleJob(triggerKey, trigger);
					}
				// 新添加Job
				} else {
					String newCronExpression = itemFreq.getScript() == null?"":itemFreq.getScript().trim();
					String jobName = "JOB_ITEM_FREQ_"+itemFreq.getId();
					String triggerName = "TRIGGER_ITEM_FREQ_"+itemFreq.getId();
					JobDataMap jobDataMap = new JobDataMap();
					jobDataMap.put("itemFreq_id", itemFreq.getId());
					jobDataMap.put("itemFreq_descr", itemFreq.getDescr());
		            JobDetail jobDetail= JobBuilder.newJob(SendMqJob.class).withIdentity(jobName, JOB_GROUP_NAME).usingJobData(jobDataMap).build();
		            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
		            triggerBuilder.withIdentity(triggerName, TRIGGER_GROUP_NAME);
		            triggerBuilder.startNow();
		            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(newCronExpression));
		            CronTrigger trigger = (CronTrigger) triggerBuilder.build();
		            scheduler.scheduleJob(jobDetail, trigger);  

				}
			}
			itemFreqList = ifList;
            // 启动  
            if (!scheduler.isShutdown()) {  
            	scheduler.start();  
            }  			
		} catch (SchedulerException e) {
			throw new RuntimeException(e);
		}
    	
    }
   @Override  
   public void execute(JobExecutionContext context) throws JobExecutionException {  
	   executeTaskRefresh();
   }

}
